package com.example.demo_01.service.impl;

import com.example.demo_01.mapper.StuMapper;
import com.example.demo_01.service.StuService;
import com.example.demo_01.util.ResultBean;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

@Service
public class StuServiceImpl implements StuService {

    @Autowired
    private StuMapper stuMapper;

    @Override
    public ResultBean findByParam(Map<String, String> param) {
        int pageNum = Integer.parseInt(param.get("pageNum"));
        int pageSize = Integer.parseInt(param.get("pageSize"));
        PageHelper.startPage(pageNum, pageSize);
        List<Map> list = stuMapper.findByParam(param);
        if (list != null && list.size() > 0) {
            PageInfo<Map> pageInfo = new PageInfo<>(list);
            return ResultBean.getInstance().success().setData(pageInfo);
        }
        return ResultBean.getInstance().fail("查无数据");
    }

    @Override
    public ResultBean doSave(Map<String, String> param) {
        // 检查学号是否重复
        int count = stuMapper.countById(param.get("sid")); //sid 是主键字段
        if (count > 0) {
            return ResultBean.getInstance().fail("添加学生失败：学号重复");
        }

        int row = stuMapper.save(param);
        if (row > 0) {
            return ResultBean.getInstance().success("添加学生成功");
        }
        return ResultBean.getInstance().fail("添加学生失败");
    }

    @Override
    public ResultBean doUpdate(Map<String, String> param) {
        int row = stuMapper.update(param);
        if (row > 0) {
            return ResultBean.getInstance().success("更新学生信息成功");
        }
        return ResultBean.getInstance().fail("更新学生信息失败，可能是学号不存在或未作任何更改");
    }

    @Override
    public ResultBean delete(String ids) {
        int row = stuMapper.delete(ids);
        if (row > 0) {
            return ResultBean.getInstance().success("删除学生成功");
        }
        return ResultBean.getInstance().fail("删除学生失败");
    }

    @Override
    public ResultBean getGenderRatio() {
        int maleCount = stuMapper.countByGender("男");
        int femaleCount = stuMapper.countByGender("女");
        Map<String, Integer> ratio = new HashMap<>();
        ratio.put("男", maleCount);
        ratio.put("女", femaleCount);
        return ResultBean.getInstance().success().setData(ratio);
    }

    @Override
    public ResultBean getStudentsByClass() {
        List<Map<String, Object>> classCounts = stuMapper.countStudentsByClass();
        return ResultBean.getInstance().success().setData(classCounts);
    }


}
